from django.http import JsonResponse
from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
import json
from .models import User
import hashlib

from django.core.files.storage import default_storage
from django.conf import settings
import os

import json
from .models import User, BlogPost

 
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

class UploadImageView(View):
    def post(self, request, *args, **kwargs):
        image = request.FILES.get('image')
        if not image:
            return JsonResponse({'error': 'No image provided'}, status=400)

        # 保存图片到 media 目录
        file_name = default_storage.save(image.name, ContentFile(image.read()))
        file_url = default_storage.url(file_name)

        return JsonResponse({'url': file_url})


class BlogDetailView(View):
    def get(self, request, blog_id):
        try:
            blog = BlogPost.objects.get(id=blog_id)
            return JsonResponse({
                'id': blog.id,
                'title': blog.title,
                'content': blog.content,
                'created_at': blog.created_at.isoformat(),
            }, status=200)
        except BlogPost.DoesNotExist:
            return JsonResponse({'error': '博客不存在'}, status=404)

@method_decorator(csrf_exempt, name='dispatch')
class BlogListView(View):
    def get(self, request):
        # 获取当前用户 ID（示例中用硬编码，实际应从 token 解析）
        user_id = 1  # TODO: 替换为 JWT 解析出来的用户 ID

        page = int(request.GET.get('page', 1))
        page_size = 10
        start = (page - 1) * page_size
        end = start + page_size

        try:
            user = User.objects.get(id=user_id)
            blogs = BlogPost.objects.filter(author=user).order_by('-created_at')[start:end]
            total = BlogPost.objects.filter(author=user).count()

            blog_list = [
                {
                    'id': blog.id,
                    'title': blog.title,
                    'created_at': blog.created_at.isoformat(),
                }
                for blog in blogs
            ]

            return JsonResponse({
                'results': blog_list,
                'total': total,
                'page': page,
                'page_size': page_size,
                'has_next': end < total,
            }, status=200)

        except User.DoesNotExist:
            return JsonResponse({'error': '用户不存在'}, status=400)

@method_decorator(csrf_exempt, name='dispatch')
class CreateBlogView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            title = data.get('title')
            content = data.get('content')

            # 获取用户信息（这里可以先简化为模拟登录）
            author_id = 1  # 示例作者 ID，后面可替换为 JWT 解析出来的用户 ID
            try:
                author = User.objects.get(id=author_id)
            except User.DoesNotExist:
                return JsonResponse({'error': '作者不存在'}, status=400)

            blog_post = BlogPost.objects.create(
                title=title,
                content=content,
                author=author
            )

            return JsonResponse({
                'message': '博客保存成功',
                'blog_id': blog_post.id
            }, status=201)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

@method_decorator(csrf_exempt, name='dispatch')
class UploadImageView(View):
    def post(self, request):
        file = request.FILES.get('image')
        if not file:
            return JsonResponse({'error': 'No image uploaded'}, status=400)

        # 保存图片
        file_name = default_storage.save(f'blog_images/{file.name}', file)

        # 返回完整 URL
        image_url = f'{settings.MEDIA_URL}{file_name}'
        return JsonResponse({'url': image_url})

        
@method_decorator(csrf_exempt, name='dispatch')
class LoginView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            email = data.get('email')
            password = data.get('password')

            if not email or not password:
                return JsonResponse({'error': 'Missing email or password'}, status=400)

            # 查询用户是否存在
            try:
                user = User.objects.get(email=email)
            except User.DoesNotExist:
                return JsonResponse({'error': '邮箱或密码错误'}, status=400)

            # 验证密码（这里使用和注册时相同的加密方式）
            hashed_pw = hashlib.sha256(password.encode()).hexdigest()
            if user.password != hashed_pw:
                return JsonResponse({'error': '邮箱或密码错误'}, status=400)

            # 登录成功，生成 token（模拟）
            return JsonResponse({
                'message': '登录成功',
                'token': f'token_{user.id}'  # 模拟 token
            }, status=200)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

@method_decorator(csrf_exempt, name='dispatch')  # ← 正确的方式
class RegisterView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            email = data.get('email')
            password = data.get('password')

            if not email or not password:
                return JsonResponse({'error': 'Missing email or password'}, status=400)

            # 简单加密（生产环境请使用更安全的方式）
            hashed_pw = hashlib.sha256(password.encode()).hexdigest()

            user = User.objects.create(email=email, password=hashed_pw)
            return JsonResponse({'message': 'User created successfully', 'user_id': user.id}, status=201)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)
